<?php

declare(strict_types=1);

namespace app\common\service;

use think\facade\Db;
use app\admin\common\ServiceResponse;
use app\common\Logic\DingTalk as LogicDingTalk;

class DingTalk extends \think\Service
{

    use ServiceResponse;

    protected $logic;

    public function __construct()
    {
        $this->logic = new LogicDingTalk();
    }

    /**
     * @describe 发送卡片消息类型工作通知
     * @author: Bobo
     * @date: 2025-01-13 14:34:37 
     * @param  $title [string] @required    标题
     * @param  $content [string] @required     内容
     * @param  $url [string] @required     链接
     * @param  $operatorIDList [array] @required     用户ID列
     * @param  $departmentIDList [array]      部门ID列表
     * @param  $coverImage [string]      封面图片
     * @return Renderable
     */
    public function SendActionCardJobNotificationMessage(string $title, string $content, string $url, array $operatorIDList, array $departmentIDList = [], string $coverImage = '')
    {
        if (empty($title) || empty($content) || empty($url)) {
            return $this->error(100003);
        }

        if (filter_var($url, FILTER_VALIDATE_URL) === false) {
            return $this->error(100500);
        }

        if (env('APP_ENV') == 'dev') {
            $title = $title . ' (测试环境)';
        }

        $msg = [
            "action_card" => [
                "title" => "明曦ERP",
                'markdown' => "# <span style='color: red;'>明曦ERP</span>\n\n### <span style='color: blue;'>$title</span>\n\n $content \n\n通知时间：" . date('Y-m-d H:i:s', time()),
                'single_title' => "查看详情",
                'single_url' => $url,
            ],
            "msgtype" => "action_card"
        ];

        if (!empty($coverImage)) {
            $msg['action_card']['markdown'] = "![]($coverImage) \n\n # <span style='color: red;'>明曦ERP</span>\n\n### <span style='color: blue;'>$title</span>\n\n $content \n\n通知时间：" . date('Y-m-d H:i:s', time());
        }

        $res = $this->logic->SendJobNotificationMessage($msg, $operatorIDList, $departmentIDList);

        if ($res['result']) {
            return $this->success();
        } else {
            return $this->error(500001, $res['msg']);
        }
    }


    /**
     * @describe 发送文本类型工作通知
     * @author: Bobo
     * @date: 2025-01-14 13:35:13 
     * @param [type] @required
     * @return Renderable
     */
    public function SendTextJobNotificationMessage(string $content, array $operatorIDList, $departmentIDList = [])
    {
        if (empty($content)) {
            return $this->error(100003);
        }
        $msg = [
            "text" => [
                "content" => $content . "\n\n通知时间：" . date('Y-m-d H:i:s', time()),
            ],
            "msgtype" => "text"
        ];
        $res = $this->logic->SendJobNotificationMessage($msg, $operatorIDList, $departmentIDList);


        if ($res['result']) {
            return $this->success();
        } else {
            return $this->error(500001, $res['msg']);
        }
    }



    /**
     * @describe 发送文本类型群聊消息
     * @author: Bobo
     * @date: 2025-01-15 13:41:02 
     * @param $content [string] @required 消息内容
     * @param $dingTalkGroupId [int] @required 群聊ID
     * @return Renderable
     */
    public function SendTextGroupChatMessage(string $content, int $dingTalkGroupId)
    {
        if (empty($content) || empty($dingTalkGroupId) || 0 >= $dingTalkGroupId) {
            return $this->error(100003);
        }
        $dingtalkGroupRes = Db::name('dingtalk_group')
            ->where([
                'id' => $dingTalkGroupId,
                'status' => 1,
                'is_del' => 0,

            ])
            ->field('id,openConversationId')
            ->find();
        if (empty($dingtalkGroupRes)) {
            return $this->error(100501);
        }
        $msgParam = json_encode([
            'content' => $content
        ]);

        $res = $this->logic->SendGroupChatMessage($msgParam, 'sampleText', $dingtalkGroupRes['openConversationId']);

        if ($res['result']) {
            return $this->success();
        } else {
            return $this->error(500001, $res['msg']);
        }
    }


    /**
     * @describe 发送卡片类型群聊消息
     * @author: Bobo
     * @date: 2025-01-15 13:41:15 
     * @param $title [string] @required 卡片标题
     * @param $content [string] @required 卡片内容
     * @param $url [string] @required 点击卡片后跳转的URL
     * @param $dingTalkGroupId [int] @required 群聊ID
     * @param $coverImage [string] @required 卡片封面图片
     * @return Renderable
     */
    public function SendActionCardGroupChatMessage(string $title, string $content, string $url, int $dingTalkGroupId, string $coverImage)
    {
        if (empty($title) || empty($content) || empty($url) || empty($dingTalkGroupId) || 0 >= $dingTalkGroupId) {
            return $this->error(100003);
        }

        if (filter_var($url, FILTER_VALIDATE_URL) === false) {
            return $this->error(100500);
        }

        $dingtalkGroupRes = Db::name('dingtalk_group')
            ->where([
                'id' => $dingTalkGroupId,
                'status' => 1,
                'is_del' => 0,

            ])
            ->field('id,openConversationId')
            ->find();
        if (empty($dingtalkGroupRes)) {
            return $this->error(100501);
        }

        $msgParam = json_encode([
            'title' => $title,
            'text' => "![]($coverImage)\n\n# <span style='color: red;'>明曦ERP</span>\n\n### <span style='color: blue;'>$title</span>\n\n $content\n\n通知时间：" . date('Y-m-d H:i:s', time()),
            'singleTitle' => '查看详情',
            'singleURL' => $url
        ]);

        $res = $this->logic->SendGroupChatMessage($msgParam, 'sampleActionCard', $dingtalkGroupRes['openConversationId']);

        if ($res['result']) {
            return $this->success();
        } else {
            return $this->error(500001, $res['msg']);
        }
    }

    /**
     * @describe 获取全部用户的userid 发送钉钉通知用
     * @author: Bobo 
     * @date: 2025-02-27 17:35:33 
     * @param [type] @required
     * @return Renderable
     */
    public function getAllOperatorUserId()
    {
        $noUserIDdata = Db::name('operator')
            ->where([
                'status' => 1,
                'is_del' => 0
            ])
            ->whereNull('userid')
            ->whereNotNull('unionId')
            ->field('id,unionId')
            ->select();
        $count = 0;

        if ($noUserIDdata) {
            foreach ($noUserIDdata as $key => $value) {
                $userid = $this->logic->getDingTalkUserIDWithUnionId($value['unionId']);
                // 更新operator表的userid字段
                if ($userid) {
                    Db::name('operator')->where('id', $value['id'])->update(['userid' => $userid]);
                    $count++;
                }
            }
        }
        return $this->success([], 0, '更新成功，更新了' . $count . '条数据');
    }
}
